#include "../apue.h"
#include <grp.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>

gid_t * alloc_groups(int *);
char * get_group_name(gid_t);

int main(void)
{
    gid_t * gtr;
    int g_max, real_max, i;
    gtr = alloc_groups(&g_max);

    printf("you have group:%d\n", getgroups(0, NULL));

    if ((real_max = getgroups(g_max, gtr)) == -1)
        err_sys("getgroups failed");

    printf("allow maximum %d groups, actual %d groups\n", g_max, real_max);
    printf("group list:\n");
    for (i=0; i<real_max; ++i)
        printf("%s(%i)\n",get_group_name(gtr[i]), gtr[i]);

    return 0;
}

gid_t * alloc_groups(int * max)
{

#ifdef NGROUPS_MAX
int gr_max = NGROUPS_MAX;
#else
int gr_max = sysconf(_SC_NGROUPS_MAX);
#endif

    gid_t * dtr;

    if ((dtr = (gid_t *)calloc(gr_max, sizeof(gid_t))) == NULL)
        err_sys("calloc failed");

    if (max != NULL)
        *max = gr_max;

    return dtr;
}

char * get_group_name(gid_t gid)
{
    static char name[FILENAME_MAX];

    struct group * gtr;
    if ((gtr = getgrgid(gid)) == NULL)
        name[0] = 0;
    else
        strcpy(name, gtr->gr_name);

    return name;
}
